const path = require("path");
const ffi = require("@breush/ffi-napi");
const ref = require("@breush/ref-napi");
const iconv = require("iconv-lite");

let hctpApi;

function getHctpLib(libDllPath) {
  if (hctpApi) {
    return hctpApi;
  }
  const int32 = ref.types.int32;
  const int64 = ref.types.int64;
  const uint32 = ref.types.uint32;
  const string = ref.types.CString;
  const voidPtr = ref.refType(ref.types.void);
  // const stringArray = ArrayType(string);

  // 定义C函数参数类型
  const S32 = ref.types.int32;
  const U64 = ref.types.uint64;
  const S64 = ref.types.int64;
  const U32 = ref.types.uint32;
  const Long = ref.types.long;
  const Char = ref.types.char;
  const CString = ref.types.CString;

  // // eslint-disable-next-line no-undef
  // let libDllPath = path.join(__static, 'sdk', 'libHCTP.dll');
  // //   let libDllPath = path.join('E:\\electron_ycb\\public\\sdk', 'libHCTP.dll');

  // if (process.env.NODE_ENV !== 'development') {
  //   libDllPath = path.join(process.resourcesPath, 'app.asar.unpacked', 'sdk', 'libHCTP.dll');
  // }

  const kernel32 = ffi.Library("kernel32", {
    SetDllDirectoryA: ["bool", [CString]],
  });

  kernel32.SetDllDirectoryA(toGBKPath(path.join(libDllPath, "..")));

  hctpApi = ffi.Library(libDllPath, {
    hctpGetVersion: ["string", []],
    // hctpInit: [uint64, [ref.types.CString, ref.types.CString, 'uint32']],
    // hctpInit: [int64, ['string', 'string', 'uint32']],
    hctpNewInit: [int64, ["string", "string", "uint32"]],
    hctpDeinit: [int32, [int64]],
    hctpSetLogLevel: [int32, [string]],
    hctpConnect: [int32, [int64, "pointer", "pointer"]],
    hctpDisconnect: [int32, [int64]],
    hctpNewUploadFile: [
      S32,
      [
        U64,
        Long,
        Char,
        CString,
        Char,
        CString,
        CString,
        CString,
        CString,
        "pointer",
      ],
    ],
    hctpNewDownloadFile: [
      S32,
      [U64, Long, CString, CString, CString, "pointer"],
    ],
    hctpTransferStopTaskById: [int32, [U64, S64, U32]],
    hctpGetFileMd5: ["int", ["string", "pointer"]],
    hctpNewUploadMedia: [
      S32,
      [U64, Long, CString, CString, CString, CString, CString, "pointer"],
    ],
    hctpNewDownloadMedia: [
      S32,
      [
        U64,
        Long,
        CString,
        CString,
        CString,
        CString,
        "pointer",
        "pointer",
        "int",
      ],
    ],
  });
  hctpApi.hctpSetLogLevel("INFO");
  return hctpApi;
}

// 将路径转换为 GBK 编码
function toGBKPath(originalPath) {
  const data = iconv.encode(originalPath, "gbk");
  return data;
}

module.exports = { getHctpLib, toGBKPath };
